<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" :label="$t('customer.index.keywords')">
          <el-input
            v-model="queryParams.keywords"
            :placeholder="$t('customer.index.queryKeywords')"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="customerType" :label="$t('customer.index.customerType')">
          <el-select
            v-model="queryParams.customerType"
            :placeholder="$t('common.choose')"
            :no-match-text="$t('common.choose')"
            style="width: 300px"
            @change="handleQuery"
          >
            <el-option
              v-for="item in customerTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">
            {{ $t("common.search") }}
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">{{ $t("common.reset") }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="list"
        highlight-current-row
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column :label="t('customer.index.customerName')" prop="customerName" />
        <el-table-column :label="t('customer.index.customerEmail')" prop="customerEmail" />
        <el-table-column :label="t('customer.index.customerStatus')" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.customerStatus === 0" type="warning">
              {{ t("common.status.unEnable") }}
            </el-tag>
            <el-tag v-else-if="scope.row.customerStatus === 1" type="success">
              {{ t("common.status.enable") }}
            </el-tag>
            <el-tag v-else type="danger">{{ t("common.status.disable") }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('customer.index.customerType')" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.customerType === 2" type="primary">
              {{ t("customer.index.customerTypeOptions.2") }}
            </el-tag>
            <el-tag v-else type="warning">{{ t("customer.index.customerTypeOptions.1") }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('customer.expiredAt')" prop="customerStartAt">
          <template #default="scope">
            <div v-if="scope.row.customerEndAt !== null">
              {{ dayjs(scope.row.customerEndAt * 1000).format("YYYY-MM-DD") }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('customer.leftDays')" prop="leftDays">
          <template #default="scope">
            <div v-if="scope.row.leftDays > 0">
              {{ scope.row.leftDays }}
            </div>
            <div v-else>
              <el-tag type="danger">{{ $t("customer.expired") }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.createdAt')" prop="createdAt">
          <template #default="scope">
            {{ dayjs(scope.row.createdAt).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.action')" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="'customer:renew'"
              type="primary"
              size="small"
              link
              icon="plus"
              @click="handleRenewOpenDialog(scope.row.customerId)"
            >
              {{ $t("order.renew") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="renew_dialog.visible"
      :title="renew_dialog.title"
      :width="dialogWidth"
      @close="handleRenewCloseDialog"
    >
      <el-form ref="reNewFormRef" :model="renewForm" :rules="renewRules">
        <el-form-item :label="$t('order.product_name')" prop="productId">
          <el-select
            v-model="renewForm.productId"
            :no-match-text="$t('order.choose_product')"
            :placeholder="$t('order.choose_product')"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('order.payMethod')" prop="payMethod">
          <el-radio-group v-model="renewForm.payMethod">
            <el-radio value="bank_transfer">
              {{ $t("order.payMethodOptions.bankTransfer") }}
            </el-radio>
            <el-radio value="ecpay">
              {{ $t("order.payMethodOptions.ecpay") }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('order.payStatus')" prop="status">
          <el-radio-group v-model="renewForm.status">
            <el-radio value="0">
              {{ $t("order.payStatusOptions.0") }}
            </el-radio>
            <el-radio value="1">
              {{ $t("order.payStatusOptions.1") }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleRenewSubmit">{{ t("common.confirm") }}</el-button>
          <el-button @click="handleRenewCloseDialog">{{ t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { ref } from "vue";
import dayjs from "dayjs";
defineOptions({
  name: "ExpiredCustomer",
  inheritAttrs: false,
});

const { t } = useI18n();

import CustomerAPI, { Form, Query, PageVO } from "@/api/customer/index";
import ProductAPI from "@/api/product";
import OrderAPI from "@/api/order";
const screenWidth = window.innerWidth;
const dialogWidth = screenWidth < 768 ? "90%" : "500px";
const queryFormRef = ref(ElForm);
const reNewFormRef = ref(ElForm);
const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<Query>({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
  customerType: undefined,
});

const list = ref<PageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const productOptions = ref<OptionType[]>([]);

const renew_dialog = reactive({
  title: "",
  visible: false,
});

const customerTypeOptions = ref<OptionType[]>([
  {
    label: t("customer.index.customerTypeOptions.0"),
    value: "",
  },
  {
    label: t("customer.index.customerTypeOptions.1"),
    value: 1,
  },
  {
    label: t("customer.index.customerTypeOptions.2"),
    value: 2,
  },
]);

function handleQuery() {
  loading.value = true;
  CustomerAPI.getExpiredList(queryParams)
    .then((data) => {
      list.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// reset query
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// select checkbox
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.deviceId);
}

const renewForm = ref<any>({
  title: "",
  status: undefined,
  customerId: 0,
  payMethod: undefined,
  productId: undefined,
});

function handleRenewOpenDialog(customerId?: number) {
  renew_dialog.visible = true;
  if (customerId) {
    renewForm.value.customerId = customerId;
    renew_dialog.title = t("order.renew");
    loading.value = true;
    CustomerAPI.getFormData(customerId).then((resCustomer) => {
      ProductAPI.getList({ solutionId: resCustomer.solutionId, pageNum: 1, pageSize: 10000 })
        .then((resP) => {
          if (resP.total > 0) {
            const items: Array<any> = [];
            for (const item of resP.list) {
              items.push({
                label: item.title + " - " + t("order.currencySmy") + " " + item.price + "",
                value: Number(item.id),
              });
            }
            productOptions.value = items;
            console.log(productOptions.value);
          }
        })
        .finally(() => {
          loading.value = false;
        });
    });
  } else {
    ElMessage.error(t("order.renew_error"));
  }
}

function handleRenewSubmit() {
  reNewFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      OrderAPI.add(renewForm.value)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.message);
            handleRenewCloseDialog();
            handleResetQuery();
          } else {
            ElMessage.error(res.data.message);
          }
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

// close dialog
function handleRenewCloseDialog() {
  renew_dialog.visible = false;

  reNewFormRef.value.resetFields();
  reNewFormRef.value.clearValidate();
}

onMounted(() => {
  handleQuery();
});

const renewRules = reactive({
  payMethod: [
    { required: true, message: t("common.choose") + t("order.payMethod"), trigger: "blur" },
  ],
  productId: [{ required: true, message: t("order.choose_product"), trigger: "blur" }],
  status: [{ required: true, message: t("common.choose") + t("order.payStatus"), trigger: "blur" }],
});
</script>
